#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/2 15:44
# @Author  : Swper
# @Site    : 
# @File    : views.py
# @Software: PyCharm
import datetime
import os
import random
import json

from flask import render_template, flash, redirect, url_for, make_response, request,jsonify
from app.admin.forms import AddtypeForm, ArticleForm, LoginForm, EditypeForm, SettingsForm,AddUserForm,AddFlinkForm
from app.config import Config
from app.models import *
from . import admin
from app.filters import string_time



@admin.route('/')
def index():
    return render_template('admin/index.html',title=Config.Web_Name)


@admin.route('/login/')
def login():
    form = LoginForm()
    return render_template('admin/login.html',form=form,title='管理后台')

#栏目列表
@admin.route('/arctype/')
def arctype():
    result = Arctype.query.all()
    return render_template('admin/arctype.html',title='栏目管理',result=result)

#添加栏目
@admin.route('/arctype/add',methods=['GET','POST'])
def addtype():
    #这里接收到POST过来的数据是JSON格式，但是要在Python中转换成字典格式(json)
    data = json.loads(request.form.get('data'))
    result = Arctype(
        tyname = data['tyname'],
        keywords = data['keywords'],
    )

    db.session.add(result)
    db.session.commit()
    return jsonify({"result": "success"})


#编辑栏目
@admin.route('/arctype/edit/<int:id>/',methods=['GET','POST'])
def editype(id=None):
    form = EditypeForm()
    arctype = Arctype.query.get_or_404(id)
    if form.validate_on_submit():
        data = form.data
        arctype.tyname = data['tyname']
        arctype.keywords = data['keywords']
        print(type)
        db.session.add(arctype)
        db.session.commit()
        flash("修改栏目成功！","ok")
        return redirect(url_for('admin.editype',id=id))
    return render_template('admin/arctype_edit.html',form=form,arctype=arctype,title='编辑栏目')


#删除栏目
@admin.route('/arctype/del/<int:id>/',methods=['GET'])
def deltype(id=None):
    arctype = Arctype.query.filter_by(id=id).first_or_404()
    db.session.delete(arctype)
    db.session.commit()
    return jsonify({"result": "success"})


#添加文章
@admin.route('/article/add/',methods=['GET','POST'])
def addarticle():
    form = ArticleForm()
    if form.validate_on_submit():
        data = form.data
        result = Article(
            title = data['title'],
            keywords = data['keywords'],
            type_id = data['tyname'],
            content = data['content']
        )
        print(result)
        flash("添加文章成功！",'ok')
        return url_for('admin.article')
    return render_template('admin/article.html',form=form,title='发布文章')


#文章列表
@admin.route('/article/')
def article():
    return render_template('admin/article_list.html',title='文章管理')


#友情链接
@admin.route('/flinks/')
def flink():
    result = Flink.query.all()
    return render_template('admin/flinks.html',title='友情链接',result=result)


#添加友情链接
@admin.route('/flinks/add',methods=['GET','POST'])
def addflinks():
    #这里接收到POST过来的数据是JSON格式，但是要在Python中转换成字典格式(json)
    data = json.loads(request.form.get('data'))
    result = Flink(
        webname = data['webname'],
        weburl = data['weburl'],
    )
    db.session.add(result)
    db.session.commit()
    return jsonify({"result": "success"})


#删除友情链接
@admin.route('/flinks/del/<int:id>',methods=['GET','POST'])
def delflinks(id=None):
    flink = Flink.query.filter_by(id=id).first_or_404()
    db.session.delete(flink)
    db.session.commit()
    return jsonify({"result": "success"})

#编辑友情连接
@admin.route('/flinks/edit/<int:id>/',methods=['GET','POST'])
def editflinks(id=None):
    form = AddFlinkForm()
    flink = Flink.query.get_or_404(id)
    if form.validate_on_submit():
        data = form.data
        flink.webname = data['webname']
        flink.weburl = data['weburl']
        db.session.add(flink)
        db.session.commit()
        flash("修改友情链接成功！","ok")
        return redirect(url_for('admin.editflinks',id=id))
    return render_template('admin/flinks_edit.html',form=form,flink=flink,title='编辑友情连接')



#用户管理
@admin.route('/user/')
def user():
    result = Admin.query.all()
    return render_template('admin/user.html',title='用户管理',result=result)

#添加用户
@admin.route('/user/add',methods=['GET','POST'])
def adduser():
    #这里接收到POST过来的数据是JSON格式，但是要在Python中转换成字典格式(json)
    data = json.loads(request.form.get('data'))

    result = Admin(
        name = data['username'],
        pwd = data['password'],
        email = data['email'],
        status = data['status'],
    )

    db.session.add(result)
    db.session.commit()
    return jsonify({"result": "success"})

#删除用户
@admin.route('/user/del/<int:id>',methods=['GET','POST'])
def deluser(id=None):
    user = Admin.query.filter_by(id=id).first_or_404()
    db.session.delete(user)
    db.session.commit()
    return jsonify({"result":"success"})


#编辑用户
@admin.route('/user/edit/<int:id>',methods=['GET','POST'])
def edituser(id=None):
    pass


#评论用户列表
@admin.route('/comment/')
def comment():
    return render_template('admin/comment.html',title='评论用户')


#系统配置,此处指定了数据库获取的数据ID为1的行进行更新操作。
@admin.route('/settings/',methods=['GET','POST'])
def settings(id=1):
    form = SettingsForm()
    sd = Settings.query.get(id)   #这里不能使用get_or_404 ,默认情况是不存在数据所以返回None
    if form.validate_on_submit():
        data = form.data
        if sd == None:
            result = Settings(
                weburl=data['weburl'],
                webname=data['webname'],
                record=data['record'],
                describe=data['describe'],
                keywords=data['keywords']
            )
            db.session.add(result)
            db.session.commit()
            flash("修改配置成功！", "ok")
            return redirect(url_for('admin.settings'))
        else:
            sd.weburl = data['weburl']
            sd.webname = data['webname']
            sd.record = data['record']
            sd.describe = data['describe']
            sd.keywords = data['keywords']
            db.session.add(sd)
            db.session.commit()
            flash("修改配置成功！", "ok")
        return redirect(url_for('admin.settings'))
    #查看数据
    settings = Settings.query.all()
    if len(settings) != 0:
        form.weburl.data = settings[0].weburl
        form.webname.data = settings[0].webname
        form.record.data = settings[0].record
        form.describe.data = settings[0].describe
        form.keywords.data = settings[0].keywords


    return render_template('admin/settings.html', form=form, settings=settings, title='编辑配置')



#文件上传[以下代码直接使用网友方案]
def gen_rnd_filename():
    filename_prefix = datetime.now().strftime('%Y%m%d%H%M%S')
    return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000)))

@admin.route('/ckupload/', methods=['POST', 'OPTIONS'])
def ckupload():
    """CKEditor file upload"""
    error = ''
    url = ''
    callback = request.args.get("CKEditorFuncNum")

    if request.method == 'POST' and 'upload' in request.files:
        fileobj = request.files['upload']
        print(fileobj)
        fname, fext = os.path.splitext(fileobj.filename)
        rnd_name = '%s%s' % (gen_rnd_filename(), fext)
        print(rnd_name)

        #由于多了一层目录，所以直接指定了
        filepath = os.path.join('app\static','upload', rnd_name)
        print(filepath)

        # 检查路径是否存在，不存在则创建
        dirname = os.path.dirname(filepath)
        if not os.path.exists(dirname):
            try:
                os.makedirs(dirname)
            except:
                error = 'ERROR_CREATE_DIR'
        elif not os.access(dirname, os.W_OK):
            error = 'ERROR_DIR_NOT_WRITEABLE'

        if not error:
            fileobj.save(filepath)
            url = url_for('static', filename='%s/%s' % ('upload', rnd_name))
            print(url)
    else:
        error = 'post error'

    res = """<script type="text/javascript">
  window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s');
</script>""" % (callback, url, error)

    response = make_response(res)
    response.headers["Content-Type"] = "text/html"
    return response
